package com.bjsxt;

import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

/**TreeMap 容器类
 * TreeMap和HashMap 同样实现了Map接口，所以API的用法来说没有区别
 * HashMap 效率高于TreeMap，TreeMap 是可以对键进行排序的一种容器，在
 * 需要对键排序时可选用TreeMap，TreeMap底层基于红黑树实现*/
/*注：key一定要有排序规则*/
public class TreeMapTest {
    public static void main(String[] args) {
        /*元素自身实现比效规则*/
        //实例化TreeMap  用users类
        //key里要有compareTo方法，进行比较排序
        Map<Users,String> map = new TreeMap<>();
        Users u1 = new Users("cs",19);
        Users u2 = new Users("sxt",22);
        Users u3 = new Users("admin",22);
        map.put(u1,"cs");
        map.put(u2,"sxt");
        map.put(u3,"admin");
        Set<Users> keys = map.keySet();
        for(Users key:keys){
            System.out.println(key+"------"+map.get(key));
        }
        System.out.println("-----------------");
        //通过比较器实现比较规则
        //Student 类       把比较器对象实例化出来，然后交给TreeMap的构造方法
        Map<Student,String> treeMap = new TreeMap<>(new StudentComparator());
        Student s1 = new Student("bb",19);
        Student s2 = new Student("DC",22);
        Student s3 = new Student("Cv",22);

        treeMap.put(s1,"bb");
        treeMap.put(s2,"DC");
        treeMap.put(s3,"Cv");
        Set<Student> keys1 = treeMap.keySet();
        for(Student key:keys1){
            System.out.println(key+"-----"+treeMap.get(key));
        }
        System.out.println("---------");
        Set<Map.Entry<Student,String>> entrySet = treeMap.entrySet();
        for(Map.Entry<Student,String> entry:entrySet){
            System.out.println(entry.getKey()+"-------"+entry.getValue());
        }
    }
}
